<template>
  <div>
    <el-form :inline="true" :model="form" class="custom-left-form">
      <el-form-item class="custom-label-item">
        <el-select v-model="queryParams.ID_ORG" placeholder="请选择机构" style="width: 200px">
          <el-option v-for="item in provinceOptions" :key="item.ID_ORG" :label="item.NA" :value="item.ID_ORG"/>
        </el-select>
      </el-form-item>

      <!--  日期组件   -->
      <el-form-item label="日期">
        <el-date-picker
            v-model="queryParams.date"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
            @change="changeDate">
        </el-date-picker>
      </el-form-item>

      <!-- 新增的字典数据下拉框 -->
      <el-form-item class="custom-label-item">
        <el-select
            v-model="selecteBusinessInput"
            placeholder="请选操作业务"
            style="width: 220px"
            @change="handleDictChange"
            value-key="dicType"
        >
          <el-option
              v-for="item in businessList"
              :key="item.dicType"
              :label="item.dicName"
              :value="item"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="success" @click="queryOrderData()">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="success" @click="exportData()">导出</el-button>
      </el-form-item>
    </el-form>
    <div class="check-dic-list">
      <div class="table-container">
        <el-table :data="tableData" style="width: 100%" :fit="true">
          <el-table-column fixed prop="BAH" label="病案号" min-width="110"></el-table-column>
          <el-table-column prop="ZYCS" label="住院次数" min-width="60"></el-table-column>
          <el-table-column prop="RYSJ" label="入院时间" min-width="155"></el-table-column>
          <el-table-column prop="CYSJ" label="出院时间" min-width="155"></el-table-column>
          <el-table-column prop="YZBH" label="医嘱编号" min-width="165"></el-table-column>
          <el-table-column prop="YZMC" label="医嘱名称" min-width="100"></el-table-column>
          <el-table-column prop="JIXING" label="剂型"></el-table-column>
          <el-table-column prop="GYTJ" label="给药途径"></el-table-column>
          <el-table-column prop="CFXQ" label="处方详情" min-width="220"></el-table-column>
          <el-table-column prop="KZSJ" label="开嘱时间" min-width="155"></el-table-column>
          <el-table-column prop="KZYSXM" label="开嘱医生姓名" min-width="110"></el-table-column>
          <el-table-column prop="KZYSBM" label="开嘱医生编码" min-width="110"></el-table-column>
          <el-table-column prop="YZKSZXSJ" label="医嘱开始执行时间" min-width="155"></el-table-column>
          <el-table-column prop="KSZXRYXM" label="开始执行人员姓名"></el-table-column>
          <el-table-column prop="TZSJ" label="停嘱时间" min-width="155"></el-table-column>
          <el-table-column prop="TZYSXM" label="停嘱医生姓名"></el-table-column>
          <el-table-column prop="TZYSBM" label="停嘱医生编码"></el-table-column>
          <el-table-column prop="YZTZZXSJ" label="医嘱停止执行时间" min-width="155"></el-table-column>
          <el-table-column prop="TZZXRYXM" label="停止执行人员姓名"></el-table-column>
          <el-table-column prop="YZTS" label="医嘱天数"></el-table-column>
        </el-table>
      </div>
      <!-- 分页插件 -->
      <div class="PaginationPlugin">
        <el-pagination
            v-if="pageObj"
            background
            layout="sizes, total, prev, pager, next, jumper"
            :page-size="pageObj.maxCount"
            :total="pageObj.totalCount"
            :current-page.sync="pageObj.currentPage"
            @size-change="pageObj.sizeChange"
            @current-change="pageObj.pageChange"
        />
      </div>
    </div>
  </div>
</template>

<script>
import moment from 'moment'
import JSZip from 'jszip'
import FileSaver from 'file-saver'
import {queryOrderData} from "@/views/ThirdLevelPubHosPerforAss/InpatientAndOutUplod/inpatientAndOutUplod"

export default {
  mounted() {
    const now = new Date();
    const currentYear = now.getFullYear();
    const currentMonth = now.getMonth(); // 月份从0开始（0-11）
    // 当月第一天
    const firstDay = new Date(currentYear, currentMonth, 1);
    // 当月最后一天（下个月第一天的前一天）
    const lastDay = new Date(currentYear, currentMonth + 1, 0);
    // 设置默认日期范围
    this.queryParams.date = [firstDay, lastDay];
  },
  data() {
    return {
      //业务下拉框
      businessList: [
        {
          dicName: '医嘱:住院医嘱数据导出',
          dicType: '1',
          viewName: 'interface.V_PCZYY_SJGLYYJXKH_ZYYZ',
          chunkSize: 5000,
          fileName: 'TCMMS51087_平昌县中医医院'
        }
        // {dicName: 'TCMMS51087_平昌县中医医院', dicType: '2', viewName: 'interface.V_PCZYY_SJGLYYJXKH_MZYZ', chunkSize: 20}
      ],
      selecteBusinessInput: null,  // 用于存储选中的字典项对象
      commonparams: {
        page: 1,
        size: 10
      },
      pageObj: {
        maxCount: 10,
        totalCount: 0,
        currentPage: 1,
        sizeChange: (page) => {
          this.handleSizeChange(page)
        },
        pageChange: (page) => {
          this.paginationPluginpageChange(page)
        }
      },
      pickerOptions: {
        // 禁用日期规则
        disabledDate(time) {
          return time.getTime() > Date.now() - 86400000
        }
      },
      queryParams: {ID_ORG: '68401005caaa060001b96f9f', date: []},
      provinceOptions: [{ID_ORG: '68401005caaa060001b96f9f', NA: '平昌县中医医院'}],
      form: {},
      tableData: []
    }
  },
  methods: {
    async exportData() {
      debugger
      if (!this.selecteBusinessInput) {
        this.$message.error('请选择操作业务')
        return false
      }

      try {
        // 1. 显示加载中提示
        this.$message({
          type: 'loading',
          message: '正在导出数据，请稍候...',
          duration: 0, // 持续显示
          forbidClick: true,
          showClose: true // 可选：显示关闭按钮
        });

        // 2. 获取所有页的数据
        const allData = await this.getAllTableData();

        if (allData.length === 0) {
          this.$message.warning('没有数据可导出');
          return;
        }

        // 3. 处理数据并生成ZIP文件
        await this.processAndDownloadData(allData);

        // 4. 提示导出成功
        this.$message.success(`数据导出成功，共${allData.length}条记录，分为${Math.ceil(allData.length / this.selecteBusinessInput.chunkSize)}个文件`);
      } catch (error) {
        console.error('导出失败:', error);
        this.$message.error('导出失败，请重试');
      } finally {
        // 关闭加载提示
        this.$message.closeAll();
      }
    },

    /**
     * 处理数据并下载：每个分片生成一个独立ZIP，每个ZIP包含1个CSV
     */
    async processAndDownloadData(allData) {
      debugger
      const {chunkSize,fileName} = this.selecteBusinessInput;
      let headers, fields;

      //获取年份
      const startYear = moment(this.queryParams.date[0]).year();

      // 根据业务类型确定CSV的表头和字段
      if (Array.isArray(allData) && allData.length > 0) {
        // 取 allData 的第一个对象（若需其他对象，可改索引，如 allData[1]）,提取该对象的所有 key，返回数组（如 ["aa", "bb", "cc"]）
        headers = Object.keys(allData[0]);
        fields = Object.keys(allData[0]);
        console.log("提取的对象key：", headers); // 打印结果，方便调试
      } else {
        // 边界处理：allData 为空或不是数组
        throw new Error("allData 为空或格式错误，无法提取 key");
      }
      const totalRecords = allData.length;
      const totalFiles = Math.ceil(totalRecords / chunkSize);
      // const timestamp = new Date().getTime(); // 同批次文件使用相同时间戳

      debugger
      // 分割数据并生成ZIP（每个分片一个ZIP）
      for (let i = 0; i < totalFiles; i++) {
        // 关键：每次循环创建新的ZIP实例，确保每个ZIP只包含当前分片的CSV
        const zip = new JSZip();

        const startIndex = i * chunkSize;
        const endIndex = Math.min(startIndex + chunkSize, totalRecords);
        const chunkData = allData.slice(startIndex, endIndex); // 当前分片数据（如第1次：0-9，第2次：10-19...）

        // 转换当前分片为CSV
        const csvContent = this.baseConvertToCsv(chunkData, headers, fields);

        // 向当前ZIP添加唯一的CSV（文件名含分片序号和总片数）
        zip.file(
            `${fileName}_${startYear}_${i + 1}.csv`, // 如：业务名_1_4.csv（第1个，共4个）
            csvContent,
            {binary: false}
        );

        // 生成当前ZIP文件
        const content = await zip.generateAsync({type: "blob"}, (metadata) => {
          const progress = Math.round(metadata.percent);
          console.log(`第${i + 1}/${totalFiles}个文件压缩进度: ${progress}%`);
        });

        // 下载当前ZIP（文件名含分片序号） TCMMS61003_西安中医医院_2024_1
        FileSaver.saveAs(
            content,
            `${fileName}_${startYear}_${i + 1}.zip` // 如：业务名_1_4_123456.zip
        );
      }
    },

    // 获取所有页的数据
    async getAllTableData() {
      const originalPageNum = this.commonparams.page;
      const originalPageSize = this.commonparams.size;
      const allData = [];

      try {
        // 先获取第一页数据，确定总页数
        this.commonparams.page = 1;
        this.commonparams.size = 1000; // 每次获取1000条，可根据实际情况调整

        const firstPageData = await this.fetchPageData();
        allData.push(...firstPageData.data);

        // 计算总页数
        const totalPages = Math.ceil(firstPageData.total / this.commonparams.size);

        // 逐页获取剩余数据
        for (let page = 2; page <= totalPages; page++) {
          this.commonparams.page = page;
          const pageData = await this.fetchPageData();
          allData.push(...pageData.data);
        }

        return allData;
      } finally {
        // 恢复原始分页参数
        this.commonparams.page = originalPageNum;
        this.commonparams.size = originalPageSize;
      }
    },

    // 获取单页数据
    async fetchPageData() {
      const start = this.queryParams.date ? moment(this.queryParams.date[0]).format('YYYY-MM-DD') : '';
      const end = this.queryParams.date ? moment(this.queryParams.date[1]).format('YYYY-MM-DD') : '';

      const params = {
        pageSize: this.commonparams.size,
        pageNum: this.commonparams.page,
        beginTime: start,
        endTime: end,
        dicName: this.queryParams.dicName,
        dicType: this.queryParams.dicType,
        idOrg: this.queryParams.ID_ORG,
        viewName: this.queryParams.viewName
      };

      return await queryOrderData(params);
    },

    /**
     * CSV转换基础方法
     */
    baseConvertToCsv(data, headers, fields) {
      if (!data || data.length === 0) return ''

      // 处理表头
      const processedHeaders = headers.map(header =>
          `"${header.toString().replace(/"/g, '""')}"`
      )

      // 构建CSV内容
      let csv = processedHeaders.join(',') + '\n'

      // 添加数据行
      data.forEach(row => {
        const values = fields.map(field => {
          const value = row[field] || '';
          // 处理特殊字符
          return `"${value.toString()
              .replace(/"/g, '""')
              .replace(/\n/g, ' ')
              .replace(/\r/g, '')}"`;
        });
        csv += values.join(',') + '\n';
      });

      return csv;
    },

    // 处理字典选择变化
    handleDictChange(selectedItem) {
      debugger
      if (selectedItem) {
        // 获取选中项的dicName和dicType
        console.log('选中的业务名称:', selectedItem.dicName);
        console.log('选中的业务类型:', selectedItem.dicType);
        console.log('选中的业务视图:', selectedItem.viewName);

        // 也可以将值存储到查询参数中，方便后续查询使用
        this.queryParams.dicName = selectedItem.dicName;
        this.queryParams.dicType = selectedItem.dicType;
        this.queryParams.viewName = selectedItem.viewName;
      } else {
        // 清除选中状态时的处理
        this.queryParams.dicName = '';
        this.queryParams.dicType = '';
        this.queryParams.viewName = '';
      }
    },

    //当日期变化时,处理事件
    changeDate() {
      this.queryOrderData()
    },

    async queryOrderData() {
      debugger
      if (!this.selecteBusinessInput) {
        this.$message.error('请选择操作业务')
        return false
      }

      const start = moment(this.queryParams.date[0]).format('YYYY-MM-DD')
      const end = moment(this.queryParams.date[1]).format('YYYY-MM-DD')
      let params = {
        pageSize: this.commonparams.size,
        pageNum: this.commonparams.page,
        beginTime: start,
        endTime: end,
        dicName: this.queryParams.dicName || '',
        dicType: this.queryParams.dicType || '',
        idOrg: this.queryParams.ID_ORG,
        viewName: this.queryParams.viewName || ''
      }

      try {
        const res = await queryOrderData(params)
        if (res.code === 99) {
          this.$message.error(res.msg)
          return false;
        }
        console.log('返回:', res)
        this.tableData = res.data || []
        this.pageObj.totalCount = res.total || 0

      } catch (error) {
        console.error('查询中心账单信息失败:', error)
        this.ybzxList = []
        this.pageObj.totalCount = 0
      }
    },

    handleSizeChange(page) {
      this.commonparams.size = page
      this.commonparams.page = 1
      this.pageObj.maxCount = page
      this.pageObj.currentPage = 1
      this.queryOrderData()
    },

    // 页码变化
    paginationPluginpageChange(val) {
      this.commonparams.page = val
      this.queryOrderData()
    }
  }
}
</script>

<style scoped>
/* 核心左对齐样式 */
.custom-left-form {
  display: flex;
  flex-wrap: wrap;
  align-items: left;
}

::v-deep .custom-label-item {
  font-size: var(--label-font-size, 20px) !important;
  color: var(--label-color, red) !important; /* 默认颜色 */
  /* font-weight: var(--label-weight, normal);*/
}

::v-deep .ellipsis-text {
  display: inline-block;
  max-width: 80%;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  vertical-align: middle;
}

/* 基础表格样式 */
::v-deep .el-table {
  border: 1px solid #000 !important;
  border-color: #000 !important; /* 表格外边框 */
}

/* 单元格边框设置 */
::v-deep .el-table td,
::v-deep .el-table th {
  border: 1px solid #000 !important;
  border-color: #000 !important; /* 单元格边框 */
}

/* 表头专属样式 */
::v-deep .el-table th {
  font-weight: 900 !important; /* 数字加粗级别（比bold更粗） */
  color: #000 !important; /* 表头文字颜色 */
  background-color: #f5f7fa !important; /* 保留默认背景色 */
}
</style>